from django.contrib.auth import authenticate
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from apps.user.models import UserModel
from utils.common import date_format


class LoginSerializer(JSONWebTokenSerializer):
    """重写登录响应逻辑"""
    def validate(self, attrs):
        credentials = {
            'username': attrs.get('username'),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                payload = jwt_payload_handler(user)
                return {
                    'token': jwt_encode_handler(payload),
                    'user': user
                }
            else:
                if UserModel.objects.filter(username=credentials["username"]).count() == 0:
                    raise serializers.ValidationError({"username": "账号不存在！"})
                else:
                    raise serializers.ValidationError({"password": "密码错误！"})


class RegisterModelSerializer(serializers.ModelSerializer):
    # 添加确认密码和token字段
    confirm_password = serializers.CharField(label="确认密码", help_text="确认密码", min_length=6, max_length=20,
                                             write_only=True)
    token = serializers.CharField(label="Token认证", help_text="Token认证", read_only=True)

    class Meta:
        model = UserModel
        fields = ["id", "username", "nickname", "email", "password", "confirm_password", "phone", "token"]

        extra_kwargs = {
            "username": {
                "min_length": 2,
                "max_length": 20,
                "error_messages": {
                    "min_length": "账号长度为 2-20 个字符！",
                    "max_length": "账号长度为 2-20 个字符！"
                }
            },
            "nickname": {
                "min_length": 2,
                "max_length": 20,
                "error_messages": {
                    "min_length": "昵称长度为 2-20 个字符！",
                    "max_length": "昵称长度为 2-20 个字符！"
                }
            },
            # "email": {
            #     "label": "邮箱",
            #     "help_text": "邮箱",
            #     "validators": [UniqueValidator(queryset=UserModel.objects.all(), message="该邮箱已被注册！")]
            # },
            "password": {
                "label": "密码",
                "help_text": "密码",
                "min_length": 6,
                "max_length": 20,
                "write_only": True,
                "error_messages": {
                    "min_length": "密码长度为 6-20 个字符！",
                    "max_length": "密码长度为 6-20 个字符！"
                }
            },
            "confirm_password": {
                "write_only": True,
            },
            "phone": {
                "validators": [UniqueValidator(queryset=UserModel.objects.all(), message="该手机号码已被注册！")]
            },
        }

    def validate(self, attrs):
        if attrs["password"] != attrs["confirm_password"]:
            raise serializers.ValidationError("确认密码和密码不一致！")
        return attrs

    def create(self, validated_data):
        validated_data.pop("confirm_password")
        # 创建user
        user = UserModel.objects.create_user(**validated_data)
        # 生成token
        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)
        return user


class UserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserModel
        fields = ["id", "username", "is_superuser", "nickname", "phone", "email", "create_time"]
        extra_kwargs = {
            "create_time": {
                "read_only": True,
                "format": date_format()
            }
        }


class UserPwdModelSerializer(serializers.ModelSerializer):
    old_password = serializers.CharField(label="旧密码", help_text="旧密码", min_length=6, max_length=20, write_only=True)
    new_password = serializers.CharField(label="新密码", help_text="新密码", min_length=6, max_length=20, write_only=True)

    class Meta:
        model = UserModel
        fields = ["old_password", "new_password", "password"]
        extra_kwargs = {
            "password": {
                "write_only": True
            },
            "old_password": {
                "required": True
            },
            "new_password": {
                "required": True
            }
        }

    def update(self, instance, validated_data):
        validated_data.pop("old_password")
        validated_data.pop("new_password")
        return super().update(instance, validated_data)
